/*
 * sp004.cpp
 *
 *  Created on: 2012-11-24
 *      Author: ssx
 */


#include "sample.h"

void CSp004::InitOpenGL() {
	int iSphere;
	// Bluish background
	glClearColor(0.0f, 0.0f, .50f, 1.0f );

	// Draw everything as wire frame
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	// Randomly place the sphere inhabitants
	for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
		{
		// Pick a random location between -200 and 200 at .1 increments
		float x = (float)((rand() % 400) - 200);
		float z = (float)((rand() % 400) - 200);
		m_Spheres[iSphere].SetOrigin(x,0.0f,z);
		}
}

void CSp004::RenderOnce() {
	m_Rot += 0.5f;
	m_Camera.ApplyCameraTransform();

	// Draw the ground
	this->DrawGround();

	// Draw the randomly located spheres
	for (int i = 0; i < NUM_SPHERES; i++) {
		glPushMatrix();
		m_Spheres[i].ApplyActorTransform();
		this->MySphere(10.0f,20,20);
		glPopMatrix();
	}

	glPushMatrix();
	glTranslatef(0.0f, 0.0f, 25.0f);

	glPushMatrix();
	glRotatef(-m_Rot * 2.0f, 0.0f, 1.0f, 0.0f);
	glTranslatef(30.0f, 0.0f, 0.0f);
	this->MySphere(10.0f,20,20);
	glPopMatrix();

	glRotatef(m_Rot, 0.0f, 1.0f, 0.0f);
	gltDrawTorus(35, 15, 40, 20);
	glPopMatrix();
}

void CSp004::DrawGround() {
	GLfloat fExtent = 200.0f;
	GLfloat fStep = 10.0f;
	GLfloat y = -4.0f;
	GLfloat iLine;

	glBegin(GL_LINES);
	for (iLine = -fExtent; iLine <= fExtent; iLine += fStep) {
		glVertex3f(iLine, y, fExtent); // Draw Z lines
		glVertex3f(iLine, y, -fExtent);

		glVertex3f(fExtent, y, iLine);
		glVertex3f(-fExtent, y, iLine);
	}
	glEnd();
}

void CSp004::OnEventWndResize(int w, int h) {
	m_ScreenW = w;
	m_ScreenH = h;
	if (h == 0)
		h = 1;
	glViewport(0,0,w,h);

	GLdouble dRatio = (GLdouble)w/(GLdouble)h;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(60.0,dRatio,1.0,800.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glTranslatef(0.0f,0.0f,-300.0f);
}

void CSp004::OnEventKeyDown(SDLKey iKey) {
	if (this->IsKeyDown(SDLK_LCTRL)) {
		CSample::OnEventKeyDown(iKey);
		return;
	}
	if(iKey == SDLK_UP)
		m_Camera.MoveForward(1.0f);

	if(iKey == SDLK_DOWN)
		m_Camera.MoveForward(-1.0f);

	if(iKey == SDLK_LEFT)
		m_Camera.RotateLocalY(0.1f);

	if(iKey == SDLK_RIGHT)
		m_Camera.RotateLocalY(-0.1f);
}
